package com.xry.test1.service.impl;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xry.test1.dao.FanRepository;
import com.xry.test1.model.AirData;
import com.xry.test1.model.FanData;
import com.xry.test1.model.LightData;
import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
import com.xry.test1.service.MQTTSubscriber.MqttMessageHandler;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Objects;

@Service
public class FanServiceImpl{
    @Autowired
    //private SimpMessagingTemplate messagingTemplate; // WebSocket 消息推送

    private static final Logger LOGGER = LoggerFactory.getLogger(FanServiceImpl.class);

    @Autowired
    private MQTTSubscribe mqttSubscribe;

    Integer lastFanLevel = 0;

    FanData lastFanData = new FanData();

    @Autowired
    private AirServiceImpl airServiceImpl;

    @Autowired
    private FanRepository fanRepository;


    private boolean isAuto = false;       // 当前是否为自动模式     // 上一次发送的挡位，避免重复发

    public boolean setAutoMode() {
        isAuto = true;
        System.out.println("切换为自动模式");
        return true;
    }

    public boolean setManualMode() {
        isAuto = false;
        System.out.println("切换为手动模式");
        return true;
    }

    public boolean controlFan(int level) {
        isAuto = false;  // 一旦手动控制，就退出自动模式
        System.out.println("手动设置挡位：" + level);

        // 检查操作是否有效
        if (level < 0 || level > 3) {
            LOGGER.warn("无效的风扇操作: {}", level);
            return false;
        }

        try {
            lastFanLevel = level;
            // 发送新的灯状态到 MQTT
//            mqttSubscribe.sendMQTTMessage(FAN_CMD_TOPIC, String.valueOf(lastFanLevel), 2);
//            LOGGER.info("发送风扇控制指令: {}", lastFanLevel);

            lastFanData.setLevel(lastFanLevel);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            lastFanData.setDate(LocalDateTime.now().format(formatter));

            fanRepository.save(lastFanData);

            return true;

        } catch (Exception e) {
            LOGGER.error("发送风扇控制指令失败", e);
            return false;
        }
    }

    public Integer getLastFanLevel() {
        return lastFanLevel;
    }


    @Scheduled(fixedRate = 1000)
    public void autoControlTask() {
        if (!isAuto) return;

        int temp =airServiceImpl.getLastTemp();
        int level=0;


        if(temp>=22&&temp<25){
            level=1;
        } else if (temp>=25&&temp<27) {
            level=2;
        }else if (temp>=27) {
            level=3;
        }else{
            level=0;
        }

        //System.out.println("level: " + level);

        if (level != lastFanLevel) {
            System.out.println("自动模式：温度=" + temp + "，调整风扇至挡位 " + level);
            lastFanLevel = level;
            sendFanLevel(level);

        }
    }

    private boolean sendFanLevel(int level) {
        // 原先的发送逻辑
//        mqttSubscribe.sendMQTTMessage(FAN_CMD_TOPIC, String.valueOf(level), 2);
//        LOGGER.info("根据温度 发送风扇控制指令: {}", level);

        lastFanData.setLevel(level);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        lastFanData.setDate(LocalDateTime.now().format(formatter));


        //mysql
        fanRepository.save(lastFanData);


        return true;
    }

}

